#!/bin/bash

if [ "$EUID" -ne 0 ]; then
    sudo -E bash "$0" "$@"
    exit $?
fi

export JAVA_HOME='/home/linux_7220765258/JDK8'
export JRE_HOME="${JAVA_HOME}/jre"
export PATH="${JAVA_HOME}/bin:${PATH}"

TOMCAT_PATH='/home/linux_7220765258/Tomcat9'
EXAM_PATH='/home/linux_7220765258/Exam'

# 获取 classes 目录
CLASSES_DIR="${TOMCAT_PATH}/webapps/ROOT/WEB-INF/classes"
if [ ! -d "$CLASSES_DIR" ]; then
    echo "Classes directory does not exist, creating: $CLASSES_DIR"
    mkdir -p "$CLASSES_DIR"
    chmod 755 "$CLASSES_DIR"
fi

# 设置 classpath
CP=""
for jar in ${TOMCAT_PATH}/lib/*.jar; do
    CP="${CP}:${jar}"
done
CP=${CP#:} 

# 编译 Java 文件
if "${JAVA_HOME}/bin/javac" -cp "${CP}" -d "${EXAM_PATH}/target" "${EXAM_PATH}/code/"*.java; then
    echo "Compilation successful."
else
    echo "Compilation failed."
    exit 1
fi

# 拷贝编译后的 class 文件到 classes 目录
cp -rf "${EXAM_PATH}/target/"* "$CLASSES_DIR/"
chmod -R 755 "$CLASSES_DIR"

# 重启 Tomcat
sudo JAVA_HOME=${JAVA_HOME} JRE_HOME=${JRE_HOME} "${TOMCAT_PATH}/bin/shutdown.sh"
sleep 1
sudo JAVA_HOME=${JAVA_HOME} JRE_HOME=${JRE_HOME} "${TOMCAT_PATH}/bin/startup.sh"

echo "Tomcat has been restarted."

